package com.pojoin.cms.dao.impl.hibernate;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;

import com.pojoin.cms.dao.UserDao;
import com.pojoin.cms.domain.User;
import com.pojoin.cms.domain.persistence.UserPersistence;
import com.pojoin.cms.util.criteria.Criteria;
import com.pojoin.cms.util.criteria.CriteriaOperator;
import com.pojoin.cms.util.criteria.impl.CriteriaKeyValue;
import com.pojoin.cms.util.criteria.orderby.Orderby;
import com.pojoin.cms.util.pager.Pager;

public class UserDaoImpl extends BaseDaoHibernate<UserPersistence> implements UserDao {

	private final String baseSql = "from UserPersistence ";
	
	private UserPersistence convert(User user){
		UserPersistence u = new UserPersistence();
		u.setDeleted(user.getDeleted());
		u.setUserName(user.getUserName());
		u.setNickName(user.getNickName());
		u.setPassword(user.getPassword());
		u.setRemark(user.getRemark());
		u.setRoles(user.getRoles());
		u.setUserId(user.getUserId());
		return u;
	}
	@Override
	String getBaseSql() {
		return this.baseSql;
	}

	@Override
	public User add(User user) {
		UserPersistence u = this.convert(user);
		return this.insertObject(u);
	}

	@Override
	public void del(Long id) {
		UserPersistence user = this.getObjectById(id);
		this.deleteObject(user);
	}

	@Override
	public User update(User user) {
		UserPersistence u = this.getObjectById(user.getUserId());
//		u = this.convert(user);
		BeanUtils.copyProperties(user, u);
		return this.updateObject(u);
	}
	@Override
	public List<User> search(Criteria c, Orderby orderby, Pager pager) {
		List<UserPersistence> list = super.queryPagerObjectListByCriteriaAndOrderby(c, orderby, pager);
		List<User> userList = new ArrayList<User>();
		for(User u : list){
			userList.add(u);
		}
		return userList;
	}
	
	@Override
	public User findById(Long id) {
		return this.getObjectById(id);
	}
	@Override
	public boolean checkUserByUserName(String userName) {
		Criteria c = new CriteriaKeyValue("userName", CriteriaOperator.EQUALS, userName);
		String hql = this.getBaseSql() + " where " + c.getSQLCriteria();
		return this.objectExist(hql);
	}

}
